<!-- 通知-好友申请或群组申请列表展示 -->
<template>
    <div id='apply_container'>
        <!-- 标题盒子 -->
        <div id="title_box">
            <!--返回按钮-->
            <div id="return_btn" @click="returnHandle">
                <img src="@/public/return.png" alt="返回" srcset="">
            </div>
            <div id="title_text">{{ pageTitle }}</div>
        </div>
        <!-- 申请者列表 - 用户 -->
        <div id="applyUserList">
            <div class="applyItem" v-for="(item, index) of applyUserInfos" :key="index">
                <!-- 头像 -->
                <div class="applyUserPicture"><img :src="item.picture" alt="" srcset=""></div>
                <!-- 信息 -->
                <div class="applyInfoBox">
                    <div>{{ item.userName }}</div>
                    <div class="applyName">{{ item.email }}</div>
                </div>
                <!-- 处理按钮 -->
                <div class="handleBtns">
                    <el-button type="success" plain @click="opsHandler('agree', item)">同意</el-button>
                    <el-button type="danger" plain @click="opsHandler('reject', item)">拒绝</el-button>
                </div>
            </div>
        </div>
        <!-- 群组申请列表 -->
        <div id="group_apply_list">
            <div class="group_item" v-for="(item, index) of groupApplyList" :key="index">
                <!-- 群组头像 -->
                <div class="group_img"><img :src="item.img" alt="群组头像" srcset=""></div>
                <!-- 群组信息 -->
                <div class="apply_info">
                    <div class="group_name">{{ item.groupName }}</div>
                    <div class="group_apply_name" v-if="item.inviteType == 0">申请者：{{ item.userName }}</div>
                    <div class="group_apply_name" v-if="item.inviteType == 2">邀你加入</div>
                </div>
                <!-- 处理申请 -->
                <div class="applyHandle">
                    <el-button type="success" plain @click="opsHandle(item, 1)">同意</el-button>
                    <el-button type="warning" plain @click="opsHandle(item, 3)">拒绝</el-button>
                </div>
            </div>
        </div>
        <!-- 空申请提示 -->
        <div id="emptyApplyText" v-if="emptyApplyTips">暂无申请 -.-</div>
    </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { getValueBykey, getLoginUserId } from "@/indexDB/dbKV";
import axios from "@/public/axiosConfig";
import { ElMessage } from 'element-plus';
import { useRouter } from "vue-router";

let router = useRouter();


// 标题
let pageTitle = ref("通知");
// 申请用户信息列表
let applyUserInfos = ref([]);
// 头像地址
let userImage = ref("");
// 空申请文本提示
let emptyApplyTips = ref(true);
// 群组申请/邀请列表
let groupApplyList = ref([]);

// 挂载完毕，获取当前用户的申请通知
onMounted(() => {
    getApplyList();
    getApplyListGroup();
})

// 处理申请分发
function opsHandle(groupInfo, ops){
    // 构造请求参数对象
    let paramObj = {groupId: groupInfo.groupId, userId: groupInfo.userId}
    if(ops == 1){
        execAgree(paramObj)
        return 1;
    }
    execReject(paramObj);
}

// 同意处理
async function execAgree(paramObj){
    paramObj["ops"] = 1
    const {data: res} = await axios.put("/groupUsers/GroupApplyHandle", paramObj)
    afterHandle(res);
}

// 拒绝处理
async function execReject(paramObj){
    paramObj["ops"] = 3
    const {data: res} = await axios.put("/groupUsers/GroupApplyHandle", paramObj)
    afterHandle(res);
}

// 群组处理-后置处理器
function afterHandle(response){
    if(response.code == 0){
        showMessage("error", "操作失败");
        return 0;
    }
    showMessage("success", response.data);
    getApplyListGroup(); // 刷新申请信息
}

// 获取通知 - 用户申请
async function getApplyList() {
    // 置空
    applyUserInfos.value = [];

    // 获取当前用户ID
    let userInfo = await getValueBykey("userInfo");
    let userId = userInfo.userId;

    // 根据当前用户ID，取出用户的【好友申请】列表
    const { data: res } = await axios.get(`/friendss/getApplyFriendsInfo/${userId}`);

    if (res.code == 0) {
        checkTwoListIsNull();
        // showMessage("info", res.msg); // 错误提示 - 未查询到申请
        return 1;
    }

    // 动态添加头像字段及字段值
    for (let item of res.data) {
        let imgSrc = await randamGetImg();
        item['picture'] = imgSrc.replace('public/', '/');
    }

    // 展示申请用户列表
    applyUserInfos.value = res.data;
    checkTwoListIsNull();
    // emptyApplyTips.value = false; // 隐藏空申请提示
}

// 获取群组申请/邀请
async function getApplyListGroup() {
    groupApplyList.value = []; // 置空
    // 获取当前登录用户ID
    let loginUserId = await getLoginUserId();
    // 获取主动申请我们群组的申请信息
    const { data: res } = await axios.get(`/groupUsers/getUserInfoOfApplyGroup/${loginUserId}`);
    // 获取邀请我们的申请信息
    const { data: resBe } = await axios.get(`/groupUsers/getBeInviteGroupInfo/${loginUserId}`);
    // 赋值-追加数据
    groupApplyList.value = [...groupApplyList.value, ...res.data, ...resBe.data];

    console.log(res);

    // 遍历追加头像字段
    for (let item of groupApplyList.value) {
        let imgSrc = await randamGetImg();
        item["img"] = imgSrc.replace('public/', '/');
    }

    checkTwoListIsNull()
}

// 检查两个列表（用户和群组）是否都为空
function checkTwoListIsNull() {
    if (groupApplyList.value.length == 0 && applyUserInfos.value.length == 0) {
        emptyApplyTips.value = true;
        return 1;
    }
    emptyApplyTips.value = false;
}

// 同意/拒绝处理器
async function opsHandler(ops, args) {

    // 构造请求参数
    // 获取当前登录用户ID
    let loginUserInfo = await getValueBykey("userInfo");
    let loginUserId = loginUserInfo.userId;

    // 判断操作
    if (ops == "agree") {
        let argsObj = { userId: loginUserId, contactId: args.userID, status: 1 };
        execOps(argsObj)
    } else {
        let argsObj = { userId: loginUserId, contactId: args.userID, status: 3 };
        execOps(argsObj);
    }

}

// 同意/拒绝执行器
async function execOps(requestArgs) {
    const { data: res } = await axios.put("/friendss/updateFriendStatus", requestArgs);
    if (res.code == 0) {
        showMessage("error", "操作失败!");
        getApplyList();
        return 0;
    }

    showMessage("success", "操作成功!");
    getApplyList();
}


async function getRandomPicture() {
    userImage.value = await randamGetImg();
}

// 通用消息提示函数
function showMessage(messageType, messageText) {
    ElMessage({
        message: messageText,
        type: messageType,
    })
}

// 随机获取一张头像 
async function randamGetImg() {
    let imgs = await getValueBykey("myPictures");
    let randomIndex = Math.floor(Math.random() * imgs.length);
    return imgs[randomIndex];
}

// 返回上一页
function returnHandle() {
    router.back();
}
</script>

<style scoped>
#title_box {
    max-width: 700px;
    font-size: 16px;
    box-sizing: border-box;
    background-color: #d7e5ee;
    width: 100%;
    position: fixed;
    top: 0px;
    left: 0px;
    padding: 15px 20px;
    display: flex;
    justify-content: center;
    align-content: center;
}

#return_btn {
    position: absolute;
    left: 8px;
    top: 14px;
}

#return_btn img {
    width: 24px;
}

#applyUserList {
    margin-top: 60px;
}

.applyUserPicture img {
    width: 46px;
    border-radius: 10px;
}

.applyItem {
    display: flex;
    flex-direction: row;
    border-bottom: solid 1px #ccc8c8;
    padding: 5px 0px;
    position: relative;
}

.applyInfoBox {
    margin-left: 8px;
    font-size: 14px;
}

.applyName {
    position: relative;
    top: 3px;
}

.handleBtns {
    position: absolute;
    right: 10px;
    /* border: solid red 1px; */
    display: flex;
    justify-content: center;
    align-content: center;
    padding-top: 5px;
}

#emptyApplyText {
    display: flex;
    justify-content: center;
    font-size: 14px;
    color: #797676;
    /* margin-top: 17px; */
    padding-top: 15px;
}

#group_apply_list {
    margin-top: 60px;
}

.group_item {
    display: flex;
    border-bottom: solid 1px #d0d0d0;
    padding-bottom: 6px;
    position: relative;
}

.apply_info {
    margin-left: 7px;
}

.group_name {
    font-size: 15px;
    font-weight: 600;
}

.group_apply_name {
    font-size: 14px;
    color: #525252;
    padding-top: 2px;
}

.group_img img {
    width: 46px;
    border-radius: 10px;
}

.applyHandle{
    position: absolute;
    right: 7px;
    top: 7px;
}
</style>